package com.mercury.pattern._03_prototype._003_deep;

import java.io.*;

public class Sheep implements Cloneable, Serializable {

    String name;
    int age;
    String color;
    //羊毛类
    Wool wool;

    public Sheep(String name, int age, String color,Wool wool) {
        this.name = name;
        this.age = age;
        this.color = color;
        this.wool = wool;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }


    public Wool getWool() {
        return wool;
    }

    public void setWool(Wool wool) {
        this.wool = wool;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    /**
     * 方式1： 利用clone方式进行深拷贝
     * @return
     */
    @Override
    protected Object clone() {
        Sheep sheep = null;
        try {
            //1、先拷贝本对象--》会将基本数据类型和string拷贝
            sheep = (Sheep) super.clone();
            //2、再拷贝Wool类
            this.wool = (Wool) wool.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return sheep;
    }

    /**
     * 方式2：利用序列化进行深拷贝--》首先对象要实现序列化接口
     *
     * @return
     */
    public Object cloneObj() {
        Sheep cloneSheep = null;
        try {
            //写入字节流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream obs = new ObjectOutputStream(out);
            obs.writeObject(this);

            //分配内存，写入原始对象，生成新对象
            ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(ios);
            cloneSheep = (Sheep) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return cloneSheep;
    }
}
